﻿using FantasticMusicPlayer.lib;
using LiteDB;
using Microsoft.Web.WebView2.Core;
using Ookii.Dialogs.WinForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace TaskLiskFullscreen
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            this.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath);

        }
        private const int WS_EX_TOOLWINDOW = 0x80;

        protected override CreateParams CreateParams
        {
            get
            {
                var currentParam = base.CreateParams;
                currentParam.ExStyle |= WS_EX_TOOLWINDOW;
                return currentParam;
            }
        }

        KeyboardHook winJhook;

        private void FrmMain_Load(object sender, EventArgs e)
        {
            todoManager = new TodoTaskManager();

            cachedRenderSuite = new CachedObject<string, CaptureAndBlurSuite>(createCacheRenderSuite,4);

            SetToFullScreen();

            CopyScreen();
			var dataPath = Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "GenshinTodoManager", "webViewData");
			if(!Directory.Exists(dataPath)){
				Directory.CreateDirectory(dataPath);
			}
            Task<CoreWebView2Environment> createEnvTask = CoreWebView2Environment.CreateAsync(userDataFolder: dataPath);
            createEnvTask.Wait();
            CoreWebView2Environment env = createEnvTask.Result;
            winJhook = new KeyboardHook();
            winJhook.OnWinJPressed += WinJhook_OnWinJPressed;

            webViewMain.EnsureCoreWebView2Async(env);
            notifyIcon1.Icon = this.Icon;
            notifyIcon1.Text = "Genshin Todo Manager";
            notifyIcon1.Visible = true;

        }

        private void WinJhook_OnWinJPressed()
        {
            ShowPanel();
        }

        private void SetToFullScreen()
        {
            Screen scr = Screen.FromPoint(MousePosition);
            this.Location = scr.Bounds.Location;
            this.Size = scr.Bounds.Size;
        }

        private void CopyScreen()
        {
            Screen currentScreen = Screen.FromPoint(MousePosition);
            var resolutionStr = currentScreen.Bounds.Width+"x"+currentScreen.Bounds.Height+"x"+currentScreen.Bounds.Top+"x"+currentScreen.Bounds.Left;
            cachedRenderSuite[resolutionStr].CaptureAndBlur(currentScreen);
        }

        private CachedObject<string, CaptureAndBlurSuite> cachedRenderSuite;

        private CaptureAndBlurSuite createCacheRenderSuite(string sr)
        {
            int[] srs = sr.Split('x').Select(s => int.Parse(s)).ToArray();
            return new CaptureAndBlurSuite(srs[0], srs[1]);
        }

        class CaptureAndBlurSuite : IDisposable
        {
            public RenderSuite ScreenBuffer;
            public RenderSuite BlurBuffer;

            public CaptureAndBlurSuite( int w,int h)
            {
                var scaledSizeW = 160;
                var scaledSizeH = 160 * h / w;

                ScreenBuffer = new RenderSuite(w,h);
                BlurBuffer = new RenderSuite(scaledSizeW,scaledSizeH);
                BlurBuffer.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                BlurBuffer.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                BlurBuffer.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                BlurBuffer.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighSpeed;
            }
            GaussianBlur blurrer = new GaussianBlur(5);

            public void CaptureAndBlur(Screen screen)
            {
                var bound = screen.Bounds;
                try
                {
                    ScreenBuffer.Graphics.CopyFromScreen(screen.Bounds.Location, Point.Empty, bound.Size);
                }catch(Exception ex)
                {
                    ScreenBuffer.Graphics.Clear(Color.DarkGray);
                }

                BlurBuffer.Graphics.DrawImage(ScreenBuffer.Bitmap, 0, 0, BlurBuffer.Bitmap.Width, BlurBuffer.Bitmap.Height);
                using (Image blur = blurrer.ProcessImage(BlurBuffer.Bitmap))
                {
                    BlurBuffer.Graphics.DrawImage(blur, 0, 0, BlurBuffer.Bitmap.Width, BlurBuffer.Bitmap.Height);
                }
            }

            public void Dispose()
            {
                ScreenBuffer.Dispose();
                BlurBuffer.Dispose();
            }
        }

        private MemoryStream GetWindowBackground()
        {
            Screen currentScreen = Screen.FromPoint(MousePosition);
            var resolutionStr = currentScreen.Bounds.Width + "x" + currentScreen.Bounds.Height + "x" + currentScreen.Bounds.Top + "x" + currentScreen.Bounds.Left;
            MemoryStream ms = new MemoryStream();
            ImageCodecInfo pngEncoder = GetEncoder(ImageFormat.Jpeg);
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 99L);
            cachedRenderSuite[resolutionStr].BlurBuffer.Bitmap.Save(ms, pngEncoder, myEncoderParameters);
            ms.Position = 0;
            return ms;
        }
        private ImageCodecInfo GetEncoder(ImageFormat format)
        {

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

        private void ShowPanel()
        {
            SetToFullScreen();
            this.webViewMain.Visible = true;
            setForeground();
            if (this.Opacity < 0.01)
            {
                this.animDirection = 1;
                this.animTimer.Start();
            }
            this.TopMost = true;
            this.TopMost = false;
        }

        private void HidePanel()
        {
            this.TopMost = false;
            if (this.Opacity > 0.99)
            {
                this.animDirection = -1;
                this.animTimer.Start();
            }
        }


        int animDirection = 1;
        bool copiedScreen = false;
        private void animTimer_Tick(object sender, EventArgs e)
        {
            if (animDirection == 1)
            {
                if (!copiedScreen)
                {
                    CopyScreen();
                    copiedScreen = true;
                    webViewMain.CoreWebView2?.ExecuteScriptAsync("reloadBackgroundImage()");

                }
                this.TopMost = true;
                double currentOpacity = this.Opacity;
                currentOpacity += currentOpacity < 0.1d ? 0.015d : 0.08d;
                if (currentOpacity > 1)
                {
                    currentOpacity = 1;
                    animTimer.Enabled = false;
                    this.Activate();
                    this.TopMost = false;
                    webViewMain.CoreWebView2?.Resume();
                }
                this.Opacity = currentOpacity;
            }
            else
            {
                double currentOpacity = this.Opacity;
                currentOpacity -= 0.08d;
                if (currentOpacity < 0)
                {
                    currentOpacity = 0;
                    animTimer.Enabled = false;
                    copiedScreen = false;

                    webViewMain.CoreWebView2?.TrySuspendAsync();

                    this.webViewMain.Visible = false;
                    this.Size = new Size(4, 4);
                }
                this.Opacity = currentOpacity;
            }
        }
        

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowPanel();
        }

        private void 显示界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowPanel();
        }

        bool allowAltF4 = false;

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            allowAltF4 = true;
            Close();
            Application.Exit();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = allowAltF4 == false;
            }
            winJhook.Dispose();
        }

        #region Webview Logic

        private void webViewMain_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                webViewMain.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded;
                webViewMain.CoreWebView2.AddWebResourceRequestedFilter("http://task-internal.zyfdroid.com/*", CoreWebView2WebResourceContext.All);
                webViewMain.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
                webViewMain.CoreWebView2.Settings.IsPinchZoomEnabled = false;
                webViewMain.CoreWebView2.Settings.IsZoomControlEnabled = false;
                webViewMain.CoreWebView2.FrameNavigationStarting += WebView_FrameNavigationStarting;
                webViewMain.CoreWebView2.NavigationStarting += WebView_FrameNavigationStarting;
                webViewMain.CoreWebView2.NewWindowRequested += WebView_NewWindowRequested;
                webViewMain.CoreWebView2.Settings.IsStatusBarEnabled = false;
                resourceHandler = new ResourceHandler(webViewMain.CoreWebView2.Environment);
                webViewMain.CoreWebView2.Navigate(urlbase + "/container.html");
                hotkeyListener1.AddHotkey(new HotKey("Hide", KeyModifier.None, Keys.Escape, false, (hk) =>
                {
                    HidePanel();
                }));

                Program.ExternalRequireActivate += Program_ExternalRequireActivate;
            }
            else
            {

                if(MessageBox.Show("没有安装WebView2运行时，请升级Windows系统","启动失败",MessageBoxButtons.RetryCancel) == DialogResult.Retry)
                {
                    Process.Start(Application.ExecutablePath);
                }
                Application.Exit();
            }
        }

        private void CoreWebView2_WindowCloseRequested(object sender, object e)
        {

        }

        private void Program_ExternalRequireActivate(object sender, EventArgs e)
        {
            BeginInvoke(new Action(() => { ShowPanel(); }));
        }

        private void CoreWebView2_DOMContentLoaded(object sender, CoreWebView2DOMContentLoadedEventArgs e)
        {
            webViewMain.CoreWebView2.ExecuteScriptAsync("setUserName(\"" + Environment.UserName.Replace("\"", "").Replace("\n", "").Replace("\r", "") + "\");");
            if (Program.StartupArgs.IsMinimized)
            {
                animDirection = -1;
                Program.StartupArgs.IsMinimized = false;// clear flags
                webViewMain.CoreWebView2.TrySuspendAsync();
            }
            animTimer.Enabled = true;

        }

        string urlbase = "http://task-internal.zyfdroid.com";
        private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
        {
            if (e.Request.Uri.StartsWith(urlbase, StringComparison.OrdinalIgnoreCase))
            {
                var request = e.Request;

                string postData = null;
                if (request.Method.ToLower() == "post")
                {
                    using (StreamReader sr = new StreamReader(request.Content))
                    {
                        postData = sr.ReadToEnd();
                    }
                }

                var deferral = e.GetDeferral();

                System.Threading.SynchronizationContext.Current.Post((_) => {

                    using(deferral)
                    {

                        e.Response = HandleRequest(new Uri(e.Request.Uri), postData);
                    }
                    
                }, null);
            }
        }






        internal class ResourceHandler
        {
            private CoreWebView2Environment env;

            public ResourceHandler(CoreWebView2Environment env)
            {
                this.env = env;
            }

            internal CoreWebView2WebResourceResponse ForErrorMessage(string errMsg, HttpStatusCode errCode)
            {
                return env.CreateWebResourceResponse(null, (int)errCode, errMsg, "");
            }

            internal CoreWebView2WebResourceResponse FromFilePath(string path, string mimeType, bool autoClose)
            {
                Stream fileStream = new MemoryStream(File.ReadAllBytes(path));
                return env.CreateWebResourceResponse(fileStream, 200, "OK", "Content-Type: " + mimeType);
            }

            internal CoreWebView2WebResourceResponse FromStream(Stream s, string mimetype, bool autoDisposeStream)
            {
                return env.CreateWebResourceResponse(s, 200, "OK", "Content-Type: " + mimetype);
            }

            internal CoreWebView2WebResourceResponse FromString(string msg, Encoding encoding, string contentType)
            {
                MemoryStream ms = new MemoryStream(encoding.GetBytes(msg));
                return env.CreateWebResourceResponse(ms, 200, "OK", "Content-Type: " + contentType + ", charset=" + encoding.EncodingName);
            }
        }

        private ResourceHandler resourceHandler;


        public CoreWebView2WebResourceResponse HandleRequest(Uri uri, string postData)
        {
            try
            {
                if (uri.AbsolutePath.StartsWith("/api/image/background.jpg"))
                {
                    return resourceHandler.FromStream(GetWindowBackground(), "image/jpeg", true);
                }
                if (uri.AbsolutePath.StartsWith("/api/script/undebug.js"))
                {
                    return resourceHandler.FromString("resizeToFixedRatio=false;debugActualSize=false;", Encoding.UTF8, "text/javascript");
                }

                if (uri.AbsolutePath.StartsWith("/api/todo/"))
                {
                    return HandleApiRequest(uri.AbsolutePath, postData);
                }

                if (uri.AbsolutePath.StartsWith("/api/ui/close"))
                {
                    BeginInvoke(new Action(() =>
                    {
                        HidePanel();
                    }));
                    return resourceHandler.FromString("OK", Encoding.UTF8, "text/plain");
                }
                string localfile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "wwwroot", uri.AbsolutePath.Trim('/', '\\'));

                string path = uri.AbsolutePath;
                if (path.StartsWith("/"))
                {
                    path = path.Substring(1);
                }
                string mimetype = "text/html";
                if (path.Contains("."))
                {
                    string ext = path.Substring(path.LastIndexOf(".")).Replace(".", "");
                    mimetype = System.Web.MimeMapping.GetMimeMapping(path);
                }
                Stream s = Program.HtDocs.OpenRead(path);
                if (s != null)
                {
                    return resourceHandler.FromStream(s, mimetype, autoDisposeStream: true);
                }


                return resourceHandler.ForErrorMessage("Not Found", HttpStatusCode.NotFound);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return resourceHandler.ForErrorMessage("Internal Server Error", HttpStatusCode.InternalServerError);
            }
        }




        TodoTaskManager todoManager;

        public CoreWebView2WebResourceResponse HandleApiRequest(string path, string postData)
        {
          
            var getJson = new Func<object, CoreWebView2WebResourceResponse>(obj => resourceHandler.FromString(Newtonsoft.Json.JsonConvert.SerializeObject(obj), Encoding.UTF8, "text/json"));
            if (path.StartsWith("/api/todo/all"))
            {
                return getJson(todoManager.GetAllTask());
            }

            string byTypePrefix = "/api/todo/bytype/";
            if (path.StartsWith(byTypePrefix))
            {
                int type = int.Parse(path.Substring(byTypePrefix.Length));
                return getJson(todoManager.GetTaskByType(type));
            }

            if (path.StartsWith("/api/todo/done"))
            {
                return getJson(todoManager.GetCompletedTask());
            }

            if (path.StartsWith("/api/todo/reqfile"))
            {
                string[] result = (string[])Invoke(new Func<string[]>(() =>
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Multiselect = true;
                    if (openFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        return openFileDialog.FileNames;
                    }
                    return new string[0];
                }));

                var files = result.Select(f =>
                {
                    RelatedFile relatedFile = new RelatedFile();
                    relatedFile.Path = f;
                    relatedFile.IsDir = false;
                    relatedFile.DisplayName = Path.GetFileName(f);
                    return relatedFile;
                }).ToList();



                return getJson(files);
            }

            if (path.StartsWith("/api/todo/reqfolder"))
            {
                string[] result = (string[])Invoke(new Func<string[]>(() =>
                {
                    Ookii.Dialogs.WinForms.VistaFolderBrowserDialog openFileDialog = new Ookii.Dialogs.WinForms.VistaFolderBrowserDialog();
                    if (openFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        return new string[] { openFileDialog.SelectedPath };
                    }
                    return new string[0];
                }));


                var files = result.Select(f =>
                {
                    RelatedFile relatedFile = new RelatedFile();
                    relatedFile.Path = f;
                    relatedFile.IsDir = true;
                    relatedFile.DisplayName = new DirectoryInfo(f).Name + "/";
                    return relatedFile;
                }).ToList();



                return getJson(files);
            }

            if (path.StartsWith("/api/todo/openfile") && postData != null)
            {
                RelatedFile relatedFile = Newtonsoft.Json.JsonConvert.DeserializeObject<RelatedFile>(postData);
                openFileOrFolder(relatedFile.Path);
                return getJson(new { code = 200, msg = "ok" });
            }


            if (path.StartsWith("/api/todo/add") && postData != null)
            {
                TodoTask task = Newtonsoft.Json.JsonConvert.DeserializeObject<TodoTask>(postData);
                todoManager.AddTask(task);
                return getJson(new { code = 200, msg = "ok" });
            }

            if (path.StartsWith("/api/todo/edit") && postData != null)
            {
                TodoTask task = Newtonsoft.Json.JsonConvert.DeserializeObject<TodoTask>(postData);
                todoManager.EditTask(task);
                return getJson(new { code = 200, msg = "ok" });
            }

            if (path.StartsWith("/api/todo/delete") && postData != null)
            {
                TodoTask task = Newtonsoft.Json.JsonConvert.DeserializeObject<TodoTask>(postData);
                todoManager.DeleteTask(task);
                return getJson(new { code = 200, msg = "ok" });
            }

            if (path.StartsWith("/api/todo/complete") && postData != null)
            {
                TodoTask task = Newtonsoft.Json.JsonConvert.DeserializeObject<TodoTask>(postData);
                todoManager.CompleteTask(task);
                return getJson(new { code = 200, msg = "ok" });
            }

            // 选择图片
            if (path.StartsWith("/api/todo/img/select"))
            {
                string[] filenames = selectImage().Select(s => SaveImage(s)).ToArray();
                return getJson(filenames);
            }

            // 粘贴图片
            if (path.StartsWith("/api/todo/img/paste"))
            {
                string[] filenames = pasteImage().Select(s => SaveImage(s)).ToArray();
                return getJson(filenames);
            }

            // 处理markdown图片
            if (path.StartsWith(imageRequestPrefix))
            {
                return resourceHandler.FromStream(HandleImageRequest(path), "image/jpeg", true);
            }

            return resourceHandler.ForErrorMessage("Not Found", HttpStatusCode.NotFound);
        }

        private IEnumerable<Image> pasteImage()
        {
            Image img = null;

            try
            {
                img = Clipboard.GetImage();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                yield break;
            }
            
            if (img != null)
            {
                yield return img;
                yield break;
            }

            var imgFiles = Clipboard.GetFileDropList();
            string[] imageExtensions = { ".jpg", ".jpeg", ".bmp", ".gif", ".png" };
            if (imgFiles != null)
            {
                foreach (var item in imgFiles)
                {
                    if(imageExtensions.Any(i => item.ToLower().EndsWith(i))){
                        img = null;
                        try
                        {
                            img = Image.FromFile(item); 
                        }catch(Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                        if(img != null)
                        {
                            yield return img;
                        }
                    }
                }
            }
        }

        private IEnumerable<Image> selectImage()
        {
            string[] result = (string[])Invoke(new Func<string[]>(() =>
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "支持的图片文件|*.jpg;*.jpeg;*.bmp;*.gif;*.png";
                openFileDialog.Multiselect = true;
                if (openFileDialog.ShowDialog(this) == DialogResult.OK)
                {
                    return openFileDialog.FileNames;
                }
                return new string[0];
            }));

            string[] imageExtensions = { ".jpg", ".jpeg", ".bmp", ".gif", ".png" };
            foreach (var item in result)
            {
                if (imageExtensions.Any(i => item.ToLower().EndsWith(i)))
                {
                    Image img = null;
                    try
                    {
                        img = Image.FromFile(item);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                    if (img != null)
                    {
                        yield return img;
                    }
                }
            }

        }


        string imageDir = Path.Combine(".", "app", "images");

        private void EnsureImageDirExists()
        {
            if (!Directory.Exists(imageDir)) { Directory.CreateDirectory(imageDir); }
        }
        const string imageRequestPrefix = "/api/todo/img/get/";
        private Stream HandleImageRequest(string uri)
        {
            EnsureImageDirExists();
            string fileName = uri.Substring(imageRequestPrefix.Length);
            if (File.Exists(Path.Combine(imageDir, fileName)))
            {
                return File.OpenRead(Path.Combine(imageDir, fileName));
            }

            return new MemoryStream(Properties.Resources.lostImage);

        }
        int imageDupliateIndex = -1;
        private string SaveImage(Image img)
        {
            EnsureImageDirExists();
            string dateName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string filesuffix = ".jpg";

            string fileName = dateName + filesuffix;

            while (File.Exists(Path.Combine(imageDir, fileName)))
            {
                imageDupliateIndex++;
                fileName = fileName + "_" + imageDupliateIndex + filesuffix;
            }

            img.Save(Path.Combine(imageDir,fileName));
            img.Dispose();
            return fileName;
        }



        private void WebView_FrameNavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
        {
            if (!e.Uri.StartsWith(urlbase))
            {
                e.Cancel = true;
                System.Diagnostics.Process.Start(e.Uri);
                BeginInvoke(new Action(() => { HidePanel(); }));
            }

            Uri uri = new Uri(e.Uri);

            if (uri.AbsolutePath.StartsWith("/api/todo/v2/openfile"))
            {
                string fileName = HttpUtility.UrlDecode(uri.Query.Substring(1));
                openFileOrFolder(fileName);
                e.Cancel = true;
                BeginInvoke(new Action(() => { HidePanel(); }));
            }


        }

        private void openFileOrFolder(String fileOrFolder)
        {
            if(File.Exists(fileOrFolder))
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = $"{fileOrFolder}";
                processStartInfo.UseShellExecute = true;
                processStartInfo.WorkingDirectory = Path.GetDirectoryName(fileOrFolder);
                Process.Start(processStartInfo);
            }
            else if(Directory.Exists(fileOrFolder))
            {

                System.Diagnostics.Process.Start($"{fileOrFolder}");
            }
            else
            {
                BeginInvoke(new Action(() => { 
                    MessageBox.Show("找不到文件："+fileOrFolder,"打开失败",MessageBoxButtons.OK,MessageBoxIcon.Stop);
                })) ;
            }
        }

        private void WebView_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            if (!e.Uri.StartsWith(urlbase))
            {
                e.Handled = true;
                System.Diagnostics.Process.Start(e.Uri);
                BeginInvoke(new Action(() => { HidePanel(); }));
            }
            Uri uri = new Uri(e.Uri);

            if (uri.AbsolutePath.StartsWith("/api/todo/v2/openfile"))
            {
                string fileName = HttpUtility.UrlDecode(uri.Query.Substring(1));
                openFileOrFolder(fileName);
                e.Handled = true;
                BeginInvoke(new Action(() => { HidePanel(); }));
            }
        }

        #endregion


        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            todoManager.CloseDB();
        }



        private void 设置取消开机自启ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProcessStartInfo psi = new ProcessStartInfo(Application.ExecutablePath, Program.StartupArgs.FlagSetAutorun);
            psi.Verb = "Runas";
            try
            {
                Process.Start(psi);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }


        void setForeground()
        {
            int hForeWnd = GetForegroundWindow();
            int dwForeID = GetWindowThreadProcessId(hForeWnd, 0);
            int dwCurID = GetCurrentThreadId();
            AttachThreadInput(dwCurID, dwForeID, true);
            this.TopMost = true;
            this.Activate();
            AttachThreadInput(dwCurID, dwForeID, false);
        }

        [DllImport("user32.dll")]
        private static extern int GetForegroundWindow();
        [DllImport("user32.dll")]
        private static extern int GetWindowThreadProcessId(int hwnd, int lpdwProcessId);
        [DllImport("kernel32.dll")]
        private static extern int GetCurrentThreadId();
        [DllImport("user32.dll")]
        private static extern int AttachThreadInput(int idAttach, int idAttachTo, bool fAttach);


        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(int uAction, int uParam, IntPtr lpvParam, int fuWinIni);

        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);//设置此窗体为活动窗体
    }
}
